library(ggplot2)
library(dplyr)
library(lubridate)
library(plotly)
library(HydroGOF)
library(plotly)
library(reshape2)


#preprocess the statvar file to save as a csv. For an example see statvar_evaluation.csv
# Read Stat var file. Make sure the statvar contains basin.potsw as an output variable
# Read Stat var file
Stats.var <- read.delim("little_river_300m_stat_var.dat", header = FALSE, sep = " ", dec = ".")

#create number of lines to skip before reading data. Number of lines to skip is # of variables plus 1 
skiplines <- Stats.var[1,1] 
skiplines <- as.character(skiplines)
skiplines <- as.numeric(skiplines) +1

#create variable names from the columns and use to create column names
varnames <- Stats.var[c(2:skiplines),1:2]
varnames <- paste(varnames$V1,varnames$V2)
varnames <- as.character(varnames)
columnnames <- c('index','year','month','day','h','m','s',varnames,'null')

# Read Stat var file
Stats.var <- read.delim("little_river_300m_stat_var.dat", header = FALSE, sep = " ", dec = ".", col.names = (columnnames),skip = skiplines)
#make "date" column
Stats.var$date <- as.Date(ISOdate(Stats.var$year,Stats.var$month,Stats.var$day))

Stats.var <- Stats.var[,-14]

#Read daily observed solrad values from a csv and format date column.
#Make sure the csv has solar radiation values in Langley/day. A conversion
#might be necessary depending on the source of you solar radiation observed values.
solrad <- read.delim("daily_GHI.csv", header = TRUE, sep = ",", dec = ".")
solrad$date <- as.Date(solrad$date,"%m/%d/%Y")



#merge the simulated and observed 
file <- merge(Stats.var,solrad,by="date")

#uncalibrated but can change to trial number for each run. 

##add trial names on here #################################################################################################

write.csv(file,'uncalibrated_observed_vs_simulated.csv')

#Identify the dates with missing values 
#missing_dates <- file[rowSums(is.na(file)) > 0,]

#NA Omit. Dates with no observations will be dropped
#file <- file %>% na.omit()

#Get Goodness of Fit Statistics between sim and obs
library(hydroGOF)
obs <- file$GHI
sim <- file$basin_orad.1

ggof(sim=sim, obs=obs, dates=file$date)


#prepare for plot (ggplot prefers long format).
#for measure.vars select the columns that you want to prepare to plot
df_plot <- reshape2::melt(file,id.vars="date",
                          measure.vars=c(11,15))

df_plot$value <- as.numeric(df_plot$value)

#subset data frame rows by variable name. GHI is the observed
data_to_plot<-df_plot[df_plot$variable %in% c("GHI","basin_orad.1"),]

#time series plot (daily)
ggplot(data_to_plot) +
  geom_line(aes(x=date,y=value,col=variable)) +
  ylab("Solar Radiation (Langley/day)") +
  ggtitle("Observed v. simulated Solar Radiation")

#show values as float instead of scientific notation
options(scipen = 999) 

#create df of monthly mean for all months
df_plot_monthly <- data_to_plot %>% group_by(variable,month(date),year(date)) %>%
  summarize_at(vars(value),mean)
#make date column again 
df_plot_monthly$date <- as.Date(ISOdate(df_plot_monthly$`year(date)`,
                            df_plot_monthly$`month(date)`,1))

#plot monthly mean solar radiation
ggplot(df_plot_monthly) +
  geom_line(aes(x=date,y=value,col=variable)) +
  ylab("Solar Radiation (Langley/day)") +
  ggtitle("Monthly Mean Solar Radiation")

#create df of mean monthly solar radiation
df_plot_monthly_avg <- df_plot_monthly[,c(1,4,5)] %>% 
  group_by(month(date),variable) %>%
  summarize_at(vars(value),mean)
names(df_plot_monthly_avg)[1]<- "month"
#####################################################################################################
#Make sure this one is as close as possible. 
#####################################################################################################
#plot mean monthly solar radiation
ggplot(df_plot_monthly_avg,
       aes(x=month,y=value))+
  geom_line(aes(col=variable)) +
  scale_x_discrete(limits=c(1:12),
                   labels=c(1:12))+  #note ticks do not show here, see below
  ylab("Solar Radiation (Langley/Day") +
  ggtitle("Mean Monthly Solar Radiation")


#plot bar plot of mean monthly sim vs obs
ggplot(df_plot_monthly_avg,
       aes(fill=variable,x=factor(month),y=value))+  #factor(month) for as discrete to show labels
  geom_bar(position="dodge",stat="identity") + 
  xlab("month") + ylab("Solar Radiation (Langley/day)") +
  scale_x_discrete(breaks=c(1:12),labels=as.character(c(1:12))) +
  ggtitle("Mean Monthly Solar Radiation") +
  geom_text(aes(label=round(value)),vjust = -0.5, position=position_dodge(width=1),size=3.0) 


#sum for WATER YEARS
#make WY column
df_plot$WY <- ifelse(month(df_plot$date)<10,year(df_plot$date),year(df_plot$date)+1)
# create WY_avg data frame. Can also change to sum instead of avg
WY_avg <- df_plot %>% group_by(variable,WY) %>%
  summarize_at(vars(value),mean)

#Create a plot of WY
ggplot(WY_avg) +
  geom_line(aes(x=WY,y=value,col=variable)) +
  ylab("Solar Radiation (Langley/day)") +
  ggtitle("Water Year Total Solar Radiation")


